package com.zzw.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;


/**
 * 异步任务服务，使用@Async注解
 */
@Service
public class AsyncTaskService {

    private static final Logger logger = LoggerFactory.getLogger(AsyncTaskService.class);

    /**
     * 异步执行任务，不返回结果
     * @param taskName 任务名称
     */
    @Async("taskExecutor")
    public void executeAsyncTask(String taskName) {
        logger.info("开始执行异步任务: {}", taskName);
        try {
            // 模拟耗时操作
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("任务执行被中断: {}", e.getMessage());
        }
        logger.info("异步任务执行完成: {}, 线程名: {}", taskName, Thread.currentThread().getName());
    }

    /**
     * 异步执行任务并返回结果
     * @param taskName 任务名称
     * @return 任务执行结果
     */
    @Async("taskExecutor")
    public CompletableFuture<String> executeAsyncTaskWithResult(String taskName) {
        logger.info("开始执行带返回值的异步任务: {}", taskName);
        try {
            // 模拟耗时操作
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            CompletableFuture<String> future = new CompletableFuture<>();
            future.completeExceptionally(e);
            return future;
        }
        String result = "任务[" + taskName + "]执行结果";
        logger.info("带返回值的异步任务执行完成: {}, 线程名: {}", taskName, Thread.currentThread().getName());
        return CompletableFuture.completedFuture(result);
    }
}
